﻿Imports System.Globalization

Public Class frmOrdenCompra

    Dim controller As New ControllerSigeco.controller_compras
    Dim controllerStock As New ControllerSigeco.controller_stock

    Private Sub btnCancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancelar.Click
        Me.Close()
    End Sub

    Private _codProveedor As Integer = 0

    Public Property codProveedor() As Integer
        Get
            Return _codProveedor
        End Get
        Set(ByVal value As Integer)
            _codProveedor = value
        End Set
    End Property

    Private _codMercaderia As Integer = 0

    Public Property codMercaderia() As Integer
        Get
            Return _codMercaderia
        End Get
        Set(ByVal value As Integer)
            _codMercaderia = value
        End Set
    End Property

    Private _codMercaderiaDetalle As Integer = 0

    Public Property codMercaderiaDetalle() As Integer
        Get
            Return _codMercaderiaDetalle
        End Get
        Set(ByVal value As Integer)
            _codMercaderiaDetalle = value
        End Set
    End Property

    Private _codOrdenCompra As Integer = 0

    Public Property codOrdenCompra() As Integer
        Get
            Return _codOrdenCompra
        End Get
        Set(ByVal value As Integer)
            _codOrdenCompra = value
        End Set
    End Property

    Private _soloLectura As Boolean = False
    Public Property soloLectura() As Boolean
        Get
            Return _soloLectura
        End Get
        Set(ByVal value As Boolean)
            _soloLectura = value
        End Set
    End Property

    Private m_frmBusMercaderia As frmMercaderiaBuscador
    Public Property frmBusMercaderia() As frmMercaderiaBuscador
        Get
            Return m_frmBusMercaderia
        End Get
        Set(ByVal value As frmMercaderiaBuscador)
            m_frmBusMercaderia = value
        End Set
    End Property

    Private m_frmBusProveedor As frmProveedorBuscador
    Public Property frmBusProveedor() As frmProveedorBuscador
        Get
            Return m_frmBusProveedor
        End Get
        Set(ByVal value As frmProveedorBuscador)
            m_frmBusProveedor = value
        End Set
    End Property

    Private Sub btnBuscProveedor_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBuscProveedor.Click

        frmBusProveedor = New frmProveedorBuscador
        frmBusProveedor.ShowDialog()
        txtProveedor.Text = frmBusProveedor.ProveedorDesc
        codProveedor = frmBusProveedor.codProveedor
        If codProveedor > 0 Then
            btnBuscMercaderia.Focus()
        End If

    End Sub

    Private Sub btnBuscMercaderia_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBuscMercaderia.Click

        frmBusMercaderia = New frmMercaderiaBuscador
        frmBusMercaderia.ShowDialog()
        txtMercaderia.Text = frmBusMercaderia.MercaderiaDesc
        codMercaderia = frmBusMercaderia.codMercaderia
        If codMercaderia > 0 Then
            txtcantidad.Focus()
        End If

    End Sub

    Private Sub txtcantidad_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtcantidad.Leave
        If IsNumeric(txtcantidad.Text) And IsNumeric(txtprecio.Text) Then
            txttotal.Text = txtcantidad.Text * txtprecio.Text
        End If
    End Sub

    Private Sub frmCompras_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        dgvdetalle.AutoGenerateColumns = False
        btnImprimir.Visible = True
        cboTipo.SelectedIndex = 0

        CargarCompras()

    End Sub

    Private Sub CargarComprasDetalle()
        Try

            codMercaderia = 0
            codMercaderiaDetalle = 0
            txtMercaderia.Text = ""
            txtcantidad.Text = 1
            txtprecio.Text = 0
            txttotal.Text = 0

            Dim ds As New DataTable
            ds = controller.get_Orden_Compras_Detalles_All(oiml.dbConn, codOrdenCompra)

            If Not ds Is Nothing Then
                dgvdetalle.DataSource = ds
            Else
                dgvdetalle.DataSource = Nothing
            End If

            txtMercaderia.Focus()

        Catch ex As Exception
            MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try

    End Sub

    Dim ci As CultureInfo

    Private Sub CargarCompras()
        Try
            If codOrdenCompra > 0 Then

                Dim ds As New DataTable
                ds = controller.get_Orden_Compras_ByID(oiml.dbConn, codOrdenCompra)

                If Not ds Is Nothing Then

                    txtActualizadoFecha.Text = ds.Rows(0)("actualizadoFecha_")
                    txtActualizadoPor.Text = ds.Rows(0)("usuario")
                    txtAprobadoPor.Text = ds.Rows(0)("Administrador").ToString

                    txtProveedor.Text = ds.Rows(0)("proveedor")
                    codProveedor = ds.Rows(0)("idProveedor")

                    'ds.Rows(0)("totalFacturaSaldo").ToString("D")
                    txtTotalFactura.Text = Decimal.Parse(ds.Rows(0)("total").ToString).ToString("N0")
                    'ds.Rows(0)("totalFactura").ToString("D")

                    'ds.Rows(0)("totalFacturaIVA").ToString("D")
                    nroFactura.Text = ds.Rows(0)("nroComprobante")
                    fechaFactura.Value = ds.Rows(0)("fechaOrden")
                    fechaVto.Value = ds.Rows(0)("fechaVigencia")

                    cboTipo.Text = ds.Rows(0)("condicion")

                    ControlEstados()

                    'btnGrabar.Enabled = True
                    'btnEliminar.Enabled = True

                    CargarComprasDetalle()

                End If

            Else

                nroFactura.Focus()

            End If

        Catch ex As Exception
            MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try

    End Sub

    Private Sub ControlEstados()

        If txtAprobadoPor.Text <> "" Then

            nroFactura.Enabled = False
            fechaFactura.Enabled = False
            fechaVto.Enabled = False
            cboTipo.Enabled = False

            btnBuscMercaderia.Enabled = False
            btnBuscProveedor.Enabled = False

            btnGrabar.Enabled = False
            btnAgregarDetalle.Enabled = False

            btnConfirmar.Visible = False

            btnEliminar.Enabled = False
            btnEliminarDetalle.Enabled = False

            txtcantidad.Enabled = False
            txtprecio.Enabled = False

            btnCancelar.Focus()

        End If

    End Sub

    Private Function ValidarCampos() As Boolean

        Dim controlCampos As Boolean = False

        If nroFactura.Text = "" Or nroFactura.Text.Replace("-", "").Replace("_", "").Trim() = "" Then
            ErrorProvider1.SetError(nroFactura, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(nroFactura, "")
        End If        '

        If txtProveedor.Text = "" Then
            ErrorProvider1.SetError(txtProveedor, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(txtProveedor, "")
        End If        '


        Return controlCampos

    End Function

    Private Function ValidarCamposDetalle() As Boolean

        Dim controlCampos As Boolean = False

        If txtMercaderia.Text = "" Then
            ErrorProvider1.SetError(txtMercaderia, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(txtMercaderia, "")
        End If        '

        If txtcantidad.Text = "" Or Not IsNumeric(txtcantidad.Text) Then
            ErrorProvider1.SetError(txtcantidad, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(txtcantidad, "")
        End If        '

        If txtprecio.Text = "" Or Not IsNumeric(txtprecio.Text) Then
            ErrorProvider1.SetError(txtprecio, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(txtprecio, "")
        End If        '

        Return controlCampos

    End Function

    Private Sub btnEliminar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEliminar.Click
        If codOrdenCompra > 0 Then

            If MessageBox.Show("Desea eliminar el registro seleccionado?", "Orden de Compras", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                If controller.Delete_Orden_Compras(oiml.dbConn, codOrdenCompra, oiml.idUsuario) Then
                    Me.Close()

                Else
                    MessageBox.Show("Error: " & controller.MessageError.Message, "Orden de Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)

                End If

            End If

        End If

    End Sub

    Private Sub btnGrabar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGrabar.Click

        If ValidarCampos() Then
            Exit Sub
        End If

        If codOrdenCompra = 0 Then
            codOrdenCompra = controller.Insert_Orden_Compras(oiml.dbConn, nroFactura.Text, fechaFactura.Value, _
                                                  codProveedor, fechaVto.Value, cboTipo.Text, _
                                                  oiml.idUsuario)

            If codOrdenCompra > 0 Then
                CargarCompras()
                MessageBox.Show("Registro grabado con exito!", "Orden de Compras", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Orden de Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)

            End If

        Else
            If controller.Update_Orden_Compras(oiml.dbConn, codOrdenCompra, nroFactura.Text, fechaFactura.Value, _
                                                  codProveedor, 0, fechaVto.Value, cboTipo.Text, _
                                                  oiml.idUsuario) Then
                CargarCompras()
                MessageBox.Show("Registro grabado con exito!", "Orden de Compras", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)


            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Orden de Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)

            End If

        End If

    End Sub

    Private Sub dgvdetalle_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgvdetalle.KeyDown
        If e.KeyCode = Keys.Enter Then
            If dgvdetalle.SelectedRows.Count > 0 Then

                codMercaderiaDetalle = dgvdetalle.SelectedRows(0).Cells(0).Value

            End If
        End If
    End Sub

    Private Sub dgvdetalle_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dgvdetalle.DoubleClick
        If dgvdetalle.SelectedRows.Count > 0 Then

            codMercaderiaDetalle = dgvdetalle.SelectedRows(0).Cells(0).Value

        End If
    End Sub

    Private Sub dgvdetalle_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvdetalle.CellClick
        Try

            If dgvdetalle.SelectedRows.Count > 0 Then

                codMercaderiaDetalle = dgvdetalle.SelectedRows(0).Cells(0).Value

            End If

        Catch ex As Exception
            MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub btnEliminarDetalle_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEliminarDetalle.Click

        If codMercaderiaDetalle > 0 Then

            If MessageBox.Show("Desea eliminar el registro seleccionado?", "Orden Compras", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                If controller.Delete_Orden_Compras_Detalle(oiml.dbConn, codMercaderiaDetalle, oiml.idUsuario, codOrdenCompra) Then
                    CargarCompras()

                Else
                    MessageBox.Show("Error: " & controller.MessageError.Message, "Orden Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)

                End If

            End If

        End If

    End Sub

    Private Sub btnAgregarDetalle_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAgregarDetalle.Click

        If ValidarCampos() Then
            Exit Sub
        End If

        If ValidarCamposDetalle() Then
            Exit Sub
        End If

        If codOrdenCompra = 0 Then
            codOrdenCompra = controller.Insert_Orden_Compras(oiml.dbConn, nroFactura.Text, fechaFactura.Value, _
                                                  codProveedor, fechaVto.Value, cboTipo.Text, _
                                                  oiml.idUsuario)
        Else
            If controller.Update_Orden_Compras(oiml.dbConn, codOrdenCompra, nroFactura.Text, fechaFactura.Value, _
                                                  codProveedor, 0, fechaVto.Value, cboTipo.Text, _
                                                  oiml.idUsuario) Then
            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Orden Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)

            End If

        End If

        If codOrdenCompra > 0 And codMercaderia > 0 Then

            If controller.Insert_Orden_Compras_Detalle(oiml.dbConn, codOrdenCompra, codMercaderia, _
                                                    txtcantidad.Text, txtprecio.Text) Then
                CargarCompras()
                MessageBox.Show("Registro grabado con exito!", "Orden Compras", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If

        End If

    End Sub

    Private Sub btnConfirmar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConfirmar.Click

        If codOrdenCompra > 0 Then

            If controller.Update_Orden_Compras_Estado(oiml.dbConn, codOrdenCompra, oiml.idUsuario, oiml.idUsuario) Then
                CargarCompras()
                MessageBox.Show("Registro confirmado con exito!", "Orden Compras", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Orden Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If

        End If

    End Sub

    Private Sub cboTipo_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboTipo.SelectedIndexChanged

    End Sub

    Private Sub txtprecio_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtprecio.Leave
        If IsNumeric(txtcantidad.Text) And IsNumeric(txtprecio.Text) Then
            txttotal.Text = txtcantidad.Text * txtprecio.Text
        End If
    End Sub

    Private Sub btnAnular_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAnular.Click
        'If codCompra > 0 Then
        '    If MessageBox.Show("Desea anular el registro seleccionado?", "Compras", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

        '        If controller.Update_Compras_Estado(oiml.dbConn, codCompra, "ANULADA", oiml.idUsuario) Then
        '            Me.Close()

        '        Else
        '            MessageBox.Show("Error: " & controller.MessageError.Message, "Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)

        '        End If

        '    End If
        'End If
    End Sub

    Private Sub txtMercaderia_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtMercaderia.KeyDown
        If e.KeyCode = Keys.Enter Then
            CargarMercaderias()
        End If
    End Sub

    Private Sub CargarMercaderias()
        Try
            Dim idMarca As Integer = 0
            Dim idRubro As Integer = 0
            Dim ds As New DataTable

            ds = controllerStock.get_mercaderias_All(oiml.dbConn, 0, "", idMarca, idRubro, False, txtMercaderia.Text, 0, 0)

            If Not ds Is Nothing Then

                txtMercaderia.Text = ""
                txtMercaderia.Text = ds.Rows(0)("mercaderia")
                codMercaderia = ds.Rows(0)("idMercaderia")
                If codMercaderia > 0 Then
                    txtcantidad.Focus()
                End If

            Else

                txtMercaderia.Text = ""
                codMercaderia = 0
                MessageBox.Show("Codigo no registrado, favor verifique", "Mercaderias", MessageBoxButtons.OK, MessageBoxIcon.Information)

            End If

        Catch ex As Exception
            MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try

    End Sub

    Private Sub txtMercaderia_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtMercaderia.Enter
        txtMercaderia.Text = ""
        codMercaderia = 0
    End Sub

    Private m_frmReporte As frmReportes
    Public Property frmRpts() As frmReportes
        Get
            Return m_frmReporte
        End Get
        Set(ByVal value As frmReportes)
            m_frmReporte = value
        End Set
    End Property

    Private Sub btnImprimir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImprimir.Click

        If codOrdenCompra > 0 Then
            Dim dtFactura As New DataTable
            dtFactura = controller.get_Orden_Compras_Impresion_ByID(oiml.dbConn, codOrdenCompra)

            Dim conv As New Conversiones.Conv()


            If frmRpts Is Nothing Then
                frmRpts = New frmReportes
                'frmRpts.MdiParent = Me
                frmRpts.tipo_Reporte = "ORDENCOMPRA"
                frmRpts.datos_Reporte = dtFactura
                frmRpts.MontoLetras = "GUARANIES " & conv.enletras(txtTotalFactura.Text, False)
                frmRpts.ShowDialog()
            Else

                If Not frmRpts.Visible Then
                    frmRpts = New frmReportes()
                    'frmRpts.MdiParent = Me
                    frmRpts.tipo_Reporte = "ORDENCOMPRA"
                    frmRpts.datos_Reporte = dtFactura
                    frmRpts.MontoLetras = "GUARANIES " & conv.enletras(txtTotalFactura.Text, False)
                    frmRpts.ShowDialog()
                Else
                    frmRpts.tipo_Reporte = "ORDENCOMPRA"
                    frmRpts.datos_Reporte = dtFactura
                    frmRpts.MontoLetras = "GUARANIES " & conv.enletras(txtTotalFactura.Text, False)
                    frmRpts.Select()
                    frmRpts.Activate()
                End If

            End If

        End If

    End Sub

    Private Sub Label8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label8.Click

    End Sub
    Private Sub txtMercaderia_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtMercaderia.TextChanged

    End Sub
End Class